import 'dart:async';

import 'package:date_format/date_format.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:sptapp/api/interface/home_api.dart';
import 'package:sptapp/api/request/response_data.dart';
import 'package:sptapp/config/const.dart';
import 'package:sptapp/moudle/refresh/my_refresh.dart';
import 'package:sptapp/page/chart/line_chart.dart';
import 'package:sptapp/page/index_page.dart';
import 'package:sptapp/page/monitor/monitor_static_choose_date_dialog.dart';
import 'package:sptapp/widget/common_widget.dart';

import '../../moudle/common_info.dart';
import '../../moudle/event_bus.dart';
import '../../moudle/permiss_handler/permission_operate.dart';
import '../../widget/top_device_select.dart';
import '../chart/bar_chart.dart';
import '../home/home.dart';

class MonitorStatisticalPage extends StatefulWidget {
  const MonitorStatisticalPage({super.key});

  @override
  State<MonitorStatisticalPage> createState() => _MonitorStatisticalPageState();
}

class _MonitorStatisticalPageState extends State<MonitorStatisticalPage> with SingleTickerProviderStateMixin,AutomaticKeepAliveClientMixin {

  late TabController controller;
  ScrollController scrollController = ScrollController();
  int selIndex = 0;
  int selType = 0;

  List<DateTime> dateTimes = [DateTime.now()];
  late StreamSubscription _devicesubscription;
  List datas = [];
  List values = [];
  List bottomValues = [];
  String unit = '';
  String maxValue = '';
  bool isopen = false;
  late StreamSubscription _Slidersubscription;
  late StreamSubscription _HomeClicksubscription;
  late StreamSubscription _Timersubscription;

  late PageController _pageController;

  List _chartItems = [];

  bool isRef = true;
  String isShowBar = '0';

  List socdatas = [];
  List socvalues = [];
  String socunit = '';
  String socmaxValue = '';

  bool isShowBattery = true;

  GlobalKey<BarChartSample5State> _bottomBarKey = GlobalKey<BarChartSample5State>();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _devicesubscription = eventBus.on<DeviceInfoChange>().listen((val){
       // selIndex = 0;
       // selType = 0;
       // datas = [];
       // values = [];
       // unit = '';
       // maxValue = '';
     _getDatas(type: 1);
    });
    _Slidersubscription = eventBus.on<IndexSliderChange>().listen((val){
      setState(() {
        isopen = val.isOpen;
      });
    });
    _HomeClicksubscription = eventBus.on<HomeDataClick>().listen((val){
      Future.delayed(Duration(milliseconds: 800),(){
        if(val.index == 0){
          // setState(() {
          //   selIndex = 0;
            selType = 2;
          // });
          _getDatas();
        }else if(val.index == 1){
          // setState(() {
          //   selIndex = 0;
            selType = 4;
          // });
          _getDatas();
        }else if(val.index == 2){
          // setState(() {
          //   selIndex = 0;
            selType = 0;
          // });
          _getDatas();
        }
        else if(val.index == 3){
          // setState(() {
          //   selIndex = 0;
            selType = 3;
          // });
          _getDatas();
        }
      });
    });
    _Timersubscription = eventBus.on<IndexRefreshTimer>().listen((val){
      _getDatas(type: 1);
    });
    controller = TabController(length: 4, vsync: this);
    if(homeSelType == 0){
      selType = 2;
    }else if(homeSelType == 1){
      selType = 4;
    }else if(homeSelType == 2){
      selType = 0;
    }else if(homeSelType == 3){
      selType = 3;
    }
    _getYMRStr();
    _getDatas(type: 1);
    _pageController = PageController(initialPage: 0);
  }

  String _getTitle(int selType){
    String title = '';
    if(selType == 0){
      title = 'Charge Level'.tr;
    }else if(selType == 1){
      title = 'Battery'.tr;
    }else if(selType == 2){
      title = 'Solar Panel'.tr;
    }else if(selType == 3){
      title = 'Home Load'.tr;
    }else if(selType == 4){
      title = 'Grid'.tr;
    }else if(selType == 5){
      title = 'Generation'.tr;
    }
    return title;
  }

  String _getYMRStr(){
    DateTime dateTime = dateTimes[0];
    String month = formatDate(dateTime!, [mm]);
    String day = formatDate(dateTime, [dd]);
    String year = formatDate(dateTime, [yyyy]);
    if(selIndex == 0 ){
      if(formatDate(dateTime, [yyyy,mm,dd]) == formatDate(DateTime.now(), [yyyy,mm,dd])){
        return 'Today'.tr;
      }
      return '$day/$month/$year';
    }
    if(selIndex == 4){

      DateTime enddateTime = dateTimes[1];
      String endmonth = formatDate(enddateTime!, [mm]);
      // if(month == '01'){
      //   month = 'Jan'.tr;
      // }else if(month == '02'){
      //   month = 'Feb'.tr;
      // }else if(month == '03'){
      //   month = 'Mar'.tr;
      // }else if(month == '04'){
      //   month = 'Apr'.tr;
      // }else if(month == '05'){
      //   month = 'May'.tr;
      // }else if(month == '06'){
      //   month = 'Jun'.tr;
      // }else if(month == '07'){
      //   month = 'Jul'.tr;
      // }else if(month == '08'){
      //   month = 'Aug'.tr;
      // }else if(month == '09'){
      //   month = 'Sep'.tr;
      // }else if(month == '10'){
      //   month = 'Oct'.tr;
      // }else if(month == '11'){
      //   month = 'Nov'.tr;
      // }else if(month == '12'){
      //   month = 'Dec'.tr;
      // }
      String endday = formatDate(enddateTime, [dd]);
      String endyear = formatDate(enddateTime, [yyyy]);

      return '$day/$month/$year - $endday/$endmonth/$endyear';
    }
    if(selIndex == 2){
      if(month == '01'){
        month = 'Jan'.tr;
      }else if(month == '02'){
        month = 'Feb'.tr;
      }else if(month == '03'){
        month = 'Mar'.tr;
      }else if(month == '04'){
        month = 'Apr'.tr;
      }else if(month == '05'){
        month = 'May'.tr;
      }else if(month == '06'){
        month = 'Jun'.tr;
      }else if(month == '07'){
        month = 'Jul'.tr;
      }else if(month == '08'){
        month = 'Aug'.tr;
      }else if(month == '09'){
        month = 'Sep'.tr;
      }else if(month == '10'){
        month = 'Oct'.tr;
      }else if(month == '11'){
        month = 'Nov'.tr;
      }else if(month == '12'){
        month = 'Dec'.tr;
      }
      if(formatDate(dateTime, [yyyy]) != formatDate(DateTime.now(), [yyyy])){
        return '$month/$year';
      }
      return '$month';
    }
    if(selIndex == 3){
      return '$year';
    }
    return '$day/$month/$year';
  }

  _getDatas({int type = 2})async{

    print('baseDevice === ${baseDevice?['status']}');
    if(baseDevice?['status'].toString() == '2'){
      setState(() {});
      return;
    }

    if(type == 1){
      getDevicesList(()async{
        Map<String,dynamic> data = {
          'sn':baseDeviceNum,
          'code':selType+1,
          'dateType':selIndex,
          'startTime': formatDate(dateTimes[0], [yyyy, '-', mm, '-', dd]),
          'endTime': dateTimes.length>1? formatDate(dateTimes[1], [yyyy, '-', mm, '-', dd]):'',
        };
        ResponseData res = await HomeAPI.getHistoryData(data);
        hideLoading();
        values = [];
        datas = [];
        unit = '';
        maxValue = '';
        bottomValues = [];
        isRef = !isRef;
        if(res.code == 200 && res.data != null){
          List arr = res.data ?? [];
          if(arr.length==2){
            Map ys = arr[0] ?? {};
            Map xs = arr[1] ?? {};
            values = ys['values'] ?? [];
            unit = ys['unit'] ?? '';
            datas = xs['values'] ?? [];
            maxValue = ys['value'] ?? '';
            isShowBar = ys['isShow'].toString() ?? '0';
          }else if(arr.length==3){
            Map ybs = arr[0] ?? {};
            Map ys = arr[2] ?? {};
            Map xs = arr[1] ?? {};
            values = ys['values'] ?? [];
            bottomValues = ybs['values'] ?? [];
            unit = ys['unit'] ?? '';
            datas = xs['values'] ?? [];
            maxValue = ys['value'] ?? '';
            isShowBar = ybs['isShow'].toString() ?? '0';
          }
        }

        if(selType == 0){
          Map<String,dynamic> data = {
            'sn':baseDeviceNum,
            'code':2,
            'dateType':selIndex,
            'startTime': formatDate(dateTimes[0], [yyyy, '-', mm, '-', dd]),
            'endTime': dateTimes.length>1? formatDate(dateTimes[1], [yyyy, '-', mm, '-', dd]):'',
          };
          ResponseData res = await HomeAPI.getHistoryData(data);
          isRef = !isRef;
          if(res.code == 200 && res.data != null){
            List arr = res.data ?? [];
            if(arr.length==2){
              Map ys = arr[0] ?? {};
              Map xs = arr[1] ?? {};
              socvalues = ys['values'] ?? [];
              socunit = ys['unit'] ?? '';
              socdatas = xs['values'] ?? [];
              socmaxValue = ys['value'] ?? '';
              isShowBar = ys['isShow'].toString() ?? '0';
              print('统计详情数据展示values === $values');
            }
          }
        }

        print('basevcei  == $baseDevices');
        if(mounted){setState(() {
          if(scrollController.hasClients && selType != 0){
            scrollController.jumpTo(0);
          }
        });}
      });
      return;
    }

    Map<String,dynamic> data = {
      'sn':baseDeviceNum,
      'code':selType+1,
      'dateType':selIndex,
      'startTime': formatDate(dateTimes[0], [yyyy, '-', mm, '-', dd]),
      'endTime': dateTimes.length>1? formatDate(dateTimes[1], [yyyy, '-', mm, '-', dd]):'',
    };
    ResponseData res = await HomeAPI.getHistoryData(data);
    isRef = !isRef;
    values = [];
    datas = [];
    unit = '';
    maxValue = '';
    bottomValues = [];

    if(res.code == 200 && res.data != null){
      List arr = res.data ?? [];
      if(arr.length==2){
        Map ys = arr[0] ?? {};
        Map xs = arr[1] ?? {};
        values = ys['values'] ?? [];
        unit = ys['unit'] ?? '';
        datas = xs['values'] ?? [];
        maxValue = ys['value'] ?? '';
        isShowBar = ys['isShow'].toString() ?? '0';
        print('统计详情数据展示values === $values');
      }else if(arr.length==3){
        Map ybs = arr[0] ?? {};
        Map ys = arr[2] ?? {};
        Map xs = arr[1] ?? {};
        values = ys['values'] ?? [];
        bottomValues = ybs['values'] ?? [];
        unit = ys['unit'] ?? '';
        datas = xs['values'] ?? [];
        maxValue = ys['value'] ?? '';
        isShowBar = ybs['isShow'].toString() ?? '0';
        print('统计详情数据展示values === $values');
      }
    }

    if(selType == 0){
      Map<String,dynamic> data = {
        'sn':baseDeviceNum,
        'code':2,
        'dateType':selIndex,
        'startTime': formatDate(dateTimes[0], [yyyy, '-', mm, '-', dd]),
        'endTime': dateTimes.length>1? formatDate(dateTimes[1], [yyyy, '-', mm, '-', dd]):'',
      };
      ResponseData res = await HomeAPI.getHistoryData(data);
      isRef = !isRef;
      if(res.code == 200 && res.data != null){
        List arr = res.data ?? [];
        if(arr.length==2){
          Map ys = arr[0] ?? {};
          Map xs = arr[1] ?? {};
          socvalues = ys['values'] ?? [];
          socunit = ys['unit'] ?? '';
          socdatas = xs['values'] ?? [];
          socmaxValue = ys['value'] ?? '';
          isShowBar = ys['isShow'].toString() ?? '0';
          print('统计详情数据展示values === $values');
        }
      }
    }

    if(mounted){setState(() {
      if(scrollController.hasClients && selType != 0){
        scrollController.jumpTo(0);
      }
    });}
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _devicesubscription.cancel();
    _Slidersubscription.cancel();
    _HomeClicksubscription.cancel();
    _Timersubscription.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: defaultBlackBgColor,
      body: Container(
        width: 1.sw,
        height: 1.sh,
        child: baseDevices.isEmpty? _buildHomeNoData(1):
        baseDevice?['status'].toString() == '2'?_buildHomeNoData(2):
        Stack(
          children: [
            Column(
              children: [
                Container(
                  width: 1.sw,
                  color: defaultBlackBgColor,
                  child: Column(
                    children: [
                      SizedBox(height: ScreenUtil().statusBarHeight,),
                      _topWidget(),
                      SizedBox(height: 40.h,),
                      Container(
                        padding: EdgeInsets.symmetric(horizontal: 40.w,vertical: 0.w),
                        color: Colors.transparent,
                        alignment: Alignment.centerLeft,
                        child: Column(
                          children: [
                            Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Expanded(child: Text('${_getTitle(selType)}',style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 32.sp,
                                    height: 1.6,
                                    fontWeight: FontWeight.w600
                                ),maxLines: 1,overflow: TextOverflow.ellipsis,)),
                                //时间日期
                                Visibility(
                                  visible: true,
                                  child: Row(
                                    children: [
                                      Container(
                                        alignment: Alignment.center,
                                        height: 72.w,
                                        padding: EdgeInsets.symmetric(horizontal: 8.w),
                                        decoration: BoxDecoration(
                                            color: Color.fromRGBO(255, 255, 255, 0.1),
                                            border: Border.all(color: Color.fromRGBO(255, 255, 255, 0.5),width: 1.w),
                                            borderRadius: BorderRadius.circular(8.w)
                                        ),
                                        child: Row(
                                          mainAxisAlignment: MainAxisAlignment.center,
                                          children: [
                                            GestureDetector(
                                                onTap: (){
                                                  setState(() {
                                                    if(selIndex == 0 || selIndex == 4){
                                                      dateTimes[0] = dateTimes[0].subtract(Duration(days: 1));
                                                    }else if(selIndex == 2){
                                                      if(dateTimes[0].month-1<1){
                                                        DateTime start = DateTime(dateTimes[0].year-1, 12, 1);
                                                        DateTime end = DateTime(dateTimes[0].year-1, 12+1, 0);
                                                        dateTimes = [start,end];
                                                      }else{
                                                        DateTime start = DateTime(dateTimes[0].year, dateTimes[0].month-1, 1);
                                                        DateTime end = DateTime(dateTimes[0].year, dateTimes[0].month-1+1, 0);
                                                        dateTimes = [start,end];
                                                      }
                                                    }else if(selIndex == 3){
                                                      dateTimes = [DateTime(dateTimes[0].year-1, 1, 1),DateTime(dateTimes[0].year-1, 12, 31)];
                                                    }
                                                    _getYMRStr();
                                                  });
                                                  _getDatas();
                                                },
                                                child: Container(
                                                  color: Colors.transparent,
                                                  padding: EdgeInsets.only(left: 6.w,right: 10.w),
                                                  alignment: Alignment.centerLeft,
                                                  child: Image.asset('assets/common/static_left.png',width: 48.w,),
                                                  // color: Colors.red,
                                                )//Image.asset('assets/common/static_left_jt.png',width: 40.w,),
                                            ),
                                            GestureDetector(
                                              onTap: (){
                                                _showSelectDialog();
                                                // JhPickerTool.showDatePicker(context,
                                                //   dateType: DateType.YMD,
                                                //   value: dateTime,
                                                //   clickCallback: (val,value)async{
                                                //     print('val === '+val);
                                                //     print('value === '+val);
                                                //   },
                                                //   callBack: (DateTime time){
                                                //     setState(() {
                                                //       dateTime = time;
                                                //       _getYMRStr();
                                                //     });
                                                //     _getDatas();
                                                //   },
                                                //   title: 'Select',
                                                // );
                                              },
                                              child: Container(
                                                child: Text(_getYMRStr(),style: TextStyle(
                                                    color: Colors.white,
                                                    fontSize: 24.sp,
                                                    fontWeight: FontWeight.w400
                                                ),),
                                              ),
                                            ),
                                            GestureDetector(
                                                onTap: (){
                                                  if(selIndex == 0 && _getYMRStr() == 'Today'){
                                                    return;
                                                  }

                                                  setState(() {
                                                    if(selIndex == 0){
                                                      dateTimes[0] = dateTimes[0].add(Duration(days: 1));
                                                    }else if(selIndex == 4){
                                                      dateTimes[1] = dateTimes[1].add(Duration(days: 1));
                                                    } else if(selIndex == 2){
                                                      if(dateTimes[0].month+1>12){
                                                        DateTime start = DateTime(dateTimes[0].year+1, 1, 1);
                                                        DateTime end = DateTime(dateTimes[0].year+1, 1+1, 0);
                                                        dateTimes = [start,end];
                                                      }else{
                                                        DateTime start = DateTime(dateTimes[0].year, dateTimes[0].month+1, 1);
                                                        DateTime end = DateTime(dateTimes[0].year, (dateTimes[0].month+1)+1, 0);
                                                        dateTimes = [start,end];
                                                      }

                                                    }else if(selIndex == 3){
                                                      dateTimes = [DateTime(dateTimes[0].year+1, 1, 1),DateTime(dateTimes[0].year+1, 12, 31)];
                                                    }
                                                    _getYMRStr();
                                                  });
                                                  _getDatas();
                                                },
                                                child: Opacity(
                                                  opacity: selIndex == 0 && _getYMRStr() == 'Today'? 0.5:1,
                                                  child: Container(
                                                    padding: EdgeInsets.only(right: 6.w,left: 10.w),
                                                    color: Colors.transparent,
                                                    alignment: Alignment.centerRight,
                                                    child: Image.asset('assets/common/static_right.png',width: 48.w,),
                                                  ),
                                                )//Image.asset('assets/common/static_left_jt.png',width: 40.w,),
                                            )
                                          ],
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                            SizedBox(height: 8.w,),
                            Visibility(visible: selType == 2,child: Container(
                              color: Colors.transparent,
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Row(
                                    crossAxisAlignment: CrossAxisAlignment.end,
                                    children: [
                                      Text('${selIndex == 0? 'Daily'.tr : selIndex == 1? 'Week'.tr :selIndex == 2? 'Month'.tr : selIndex == 3 ? 'Year'.tr:''}'+' Total'.tr,style: TextStyle(
                                          color: Colors.white,
                                          fontSize: 28.sp,
                                          fontWeight: FontWeight.w400
                                      ),),
                                      SizedBox(width: 8.w,),
                                      Text('$maxValue',style: TextStyle(
                                          color: Colors.white,
                                          fontWeight: FontWeight.w400,
                                          fontSize: 56.sp,
                                          height: 1
                                      ),),
                                      SizedBox(width: 12.w,),
                                      // Text(unit,style: TextStyle(
                                      //     color: Colors.white,
                                      //     fontWeight: FontWeight.w400,
                                      //     fontSize: 36.sp,
                                      //     height: 1
                                      // ),)
                                    ],
                                  )
                                ],
                              ),
                            ),),
                            Visibility(visible: selType == 4,child: Container(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Row(
                                    crossAxisAlignment: CrossAxisAlignment.center,
                                    children: [
                                      Container(
                                        width: 12.w,
                                        height: 12.w,
                                        decoration: BoxDecoration(
                                            border: Border.all(color: themeColor,width: 1.w),
                                            borderRadius: BorderRadius.circular(12.w),
                                            gradient: LinearGradient(
                                                colors: [
                                                  Color(0x5f233292),
                                                  Color(0x0f3c55f8),
                                                ],
                                                begin: Alignment.topCenter,
                                                end: Alignment.bottomCenter
                                            )
                                        ),
                                      ),
                                      SizedBox(width: 12.w,),
                                      Text('Discharged'.tr,style: TextStyle(
                                          color: Color.fromRGBO(255, 255, 255, 0.5),
                                          fontWeight: FontWeight.w400,
                                          fontSize: 28.sp,
                                          height: 1
                                      ),)
                                    ],
                                  ),
                                  SizedBox(height: 12.w,),
                                  Row(
                                    crossAxisAlignment: CrossAxisAlignment.center,
                                    children: [
                                      Container(
                                        width: 12.w,
                                        height: 12.w,
                                        decoration: BoxDecoration(
                                            border: Border.all(color: Color(0xffCD9604),width: 1.w),
                                            borderRadius: BorderRadius.circular(12.w),
                                            gradient: LinearGradient(
                                                colors: [
                                                  Color(0x0fcd9607),
                                                  Color(0x5f674b04),
                                                ],
                                                begin: Alignment.topCenter,
                                                end: Alignment.bottomCenter
                                            )
                                        ),
                                      ),
                                      SizedBox(width: 12.w,),
                                      Text('Charged'.tr,style: TextStyle(
                                          color: Color.fromRGBO(255, 255, 255, 0.5),
                                          fontWeight: FontWeight.w400,
                                          fontSize: 28.sp,
                                          height: 1
                                      ),)
                                    ],
                                  ),
                                ],
                              ),
                            ),),
                          ],
                        ),
                      ),
                      SizedBox(height: 10.h,),
                    ],
                  ),
                ),
                Expanded(
                  child: EasyRefresh(
                    header: myRefreshHeader(),
                    onRefresh: (){
                      _getDatas(type: 1);
                    },
                    child: SingleChildScrollView(
                      controller: scrollController,
                      child: Container(
                          width: 1.sw,
                          child: Container(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                SizedBox(height: 20.h,),
                                Container(
                                  height: selType == 0 && isShowBattery? 1400.h:900.h,
                                  color: Colors.transparent,
                                  alignment: Alignment.center,
                                  // padding: EdgeInsets.symmetric(horizontal: 4),
                                  child:
                                  // _charts()
                                  EasyRefresh(
                                    child: PageView(
                                      controller: _pageController,
                                      children: _charts(),
                                      onPageChanged: (index){
                                      },
                                    ),
                                  ),
                                ),
                                SizedBox(height: 40.h,),
                                SizedBox(height: 120.h,)
                              ],
                            ),
                          )
                      ),
                    ),
                  ),
                ),
              ],
            ),
            Positioned(bottom: 0.h,left: 0,right: 0,child: Container(
              width: 1.sw,
              height: 156.h,
              decoration: BoxDecoration(
                  gradient: LinearGradient(
                      colors: [
                        Color.fromRGBO(0, 0, 0, 0),
                        Color.fromRGBO(0, 0, 0, 1),
                      ],
                      begin: Alignment.topCenter,
                      end: Alignment.bottomCenter
                  )
                // color: Colors.red
              ),
            ),),
            Positioned(bottom: 40.h,left: (1.sw-460.w)/2,child: Container(
              height: 96.w,
              width: 460.w,
              padding: EdgeInsets.symmetric(horizontal: 40.w),
              decoration: BoxDecoration(
                  color: Color.fromRGBO(45, 45, 48, 1),
                  borderRadius: BorderRadius.circular(96.w)
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  GestureDetector(
                    onTap: (){
                      setState(() {
                        values = [];
                        datas = [];
                        maxValue = '';
                        unit = '';
                        bottomValues = [];
                        socvalues=[];
                        socdatas = [];
                        socunit = '';
                        socmaxValue = '';
                        selType = 0;
                      });
                      _getDatas();
                    },
                    child: Container(
                      width: 64.w,
                      height: 64.w,
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                          color: selType == 0? themeColor: Color.fromRGBO(255, 255, 255, 0.1),
                          borderRadius: BorderRadius.circular(64.w)
                      ),
                      child: Image.asset('assets/common/static_dcgl.png',width: 40.w,),
                    ),
                  ),
                  // GestureDetector(
                  //   onTap: (){
                  //     setState(() {
                  //       selIndex = 0;
                  //       selType = 1;
                  //     });
                  //     _getDatas();
                  //   },
                  //   child: Container(
                  //     width: 64.w,
                  //     height: 64.w,
                  //     alignment: Alignment.center,
                  //     decoration: BoxDecoration(
                  //         color: Color(0xff232323),
                  //         borderRadius: BorderRadius.circular(76.w)
                  //     ),
                  //     child: Image.asset(selType == 1?'assets/common/static_battery_w.png':'assets/common/static_battery.png',width: 32.w,),
                  //   ),
                  // ),
                  GestureDetector(
                    onTap: (){
                      setState(() {
                        values = [];
                        datas = [];
                        maxValue = '';
                        unit = '';
                        bottomValues = [];
                        socvalues=[];
                        socdatas = [];
                        socunit = '';
                        socmaxValue = '';
                        selType = 3;
                      });
                      _getDatas();
                    },
                    child: Container(
                      width: 64.w,
                      height: 64.w,
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                          color: selType == 3? themeColor: Color.fromRGBO(255, 255, 255, 0.1),
                          borderRadius: BorderRadius.circular(64.w)
                      ),
                      child: Image.asset('assets/common/static_fz.png',width: 40.w,),
                    ),
                  ),
                  GestureDetector(
                    onTap: (){
                      setState(() {
                        values = [];
                        datas = [];
                        maxValue = '';
                        unit = '';
                        bottomValues = [];
                        socvalues=[];
                        socdatas = [];
                        socunit = '';
                        socmaxValue = '';
                        selType = 2;
                      });
                      _getDatas();
                    },
                    child: Container(
                      width: 64.w,
                      height: 64.w,
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                          color: selType == 2? Color(0xffCD9607): Color.fromRGBO(255, 255, 255, 0.1),
                          borderRadius: BorderRadius.circular(64.w)
                      ),
                      child: Image.asset('assets/common/static_solar.png',width: 40.w,),
                    ),
                  ),
                  GestureDetector(
                    onTap: (){
                      setState(() {
                        values = [];
                        datas = [];
                        maxValue = '';
                        unit = '';
                        bottomValues = [];
                        socvalues=[];
                        socdatas = [];
                        socunit = '';
                        socmaxValue = '';
                        selType = 4;
                      });
                      _getDatas();
                    },
                    child: Container(
                      width: 64.w,
                      height: 64.w,
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                          color: selType == 4 ? themeColor: Color.fromRGBO(255, 255, 255, 0.1),
                          borderRadius: BorderRadius.circular(64.w)
                      ),
                      child: Image.asset('assets/common/static_dw.png',width: 40.w,),
                    ),
                  ),
                  // GestureDetector(
                  //   onTap: (){
                  //     setState(() {
                  //       selIndex = 0;
                  //       selType = 5;
                  //     });
                  //     _getDatas();
                  //   },
                  //   child: Container(
                  //     width: 76.w,
                  //     height: 76.w,
                  //     alignment: Alignment.center,
                  //     decoration: BoxDecoration(
                  //         color: Color(0xff232323),
                  //         borderRadius: BorderRadius.circular(76.w)
                  //     ),
                  //     child: Image.asset(selType == 5?'assets/common/static_fdl_w.png':'assets/common/static_fdl.png',width: 32.w,),
                  //   ),
                  // ),
                ],
              ),
            ),),
          ],
        ),
      ),
    );
  }

  _showNoDeviceAlert(){
    SmartDialog.show(builder: (ctx){
      return Container(
        height: 530.w,
        padding: EdgeInsets.only(left: 48.w,right: 48.w,top: 32.w,bottom: 48.w),
        decoration: BoxDecoration(
            color: Color(0xff1E1E1E),
            borderRadius: BorderRadius.only(topLeft: Radius.circular(32.w),topRight: Radius.circular(32.w))
        ),
        child: Column(
          children: [
            Container(
              child: Row(
                children: [
                  Text('Add new device',style: TextStyle(
                      color: Colors.white,
                      fontSize: 28.sp,
                      fontWeight: FontWeight.w600
                  ),),
                  GestureDetector(
                    onTap: (){
                      SmartDialog.dismiss();
                    },
                    child: Icon(Icons.close,size: 30.sp,color: Color(0xff999999),),
                  )
                ],
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
              ),
            ),
            SizedBox(height: 100.w,),
            GestureDetector(
              onTap: (){
                SmartDialog.dismiss();
                getCameraPermission(context, (){
                  Navigator.of(context).pushNamed('ScanPage').then((val){
                    if(mounted){setState(() {});}
                  });
                });
              },
              child: Container(
                height: 84.w,
                width: 654.w,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                    color: themeColor,
                    borderRadius: BorderRadius.circular(8.w)
                ),
                child:Text('Scan Your Device',style: TextStyle(
                    color: Colors.white,
                    fontSize: 28.sp,
                    fontWeight: FontWeight.w600
                ),),
              ),
            ),
            SizedBox(height: 32.w,),
            GestureDetector(
              onTap: (){
                SmartDialog.dismiss();
                Navigator.of(context).pushNamed('MinAddDeviceInput').then((val){
                  if(mounted){setState(() {});}
                });
              },
              child: Container(
                height: 84.w,
                width: 654.w,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                    color: Color(0xff2A2A2A),
                    borderRadius: BorderRadius.circular(8.w)
                ),
                child:Text('Manual Entry'.tr,style: TextStyle(
                    color: Colors.white,
                    fontSize: 28.sp,
                    fontWeight: FontWeight.w600
                ),),
              ),
            ),
          ],
        ),
      );
    },alignment: Alignment.bottomCenter);
    // SmartDialog.show(
    //     alignment: Alignment.center,
    //     builder: (BuildContext ctx){
    //       return Container(
    //         decoration: BoxDecoration(
    //             color: Colors.white,
    //             borderRadius: BorderRadius.circular(20.w)
    //         ),
    //         margin: EdgeInsets.symmetric(horizontal: 30.w),
    //         padding: EdgeInsets.symmetric(horizontal: 30.w,vertical: 30.w),
    //         child: Container(
    //           child: Column(
    //             mainAxisSize: MainAxisSize.min,
    //             children: [
    //               Container(
    //                 child: Text(alert_waring_title.tr),
    //               ),
    //               SizedBox(height: 30.w,),
    //               Container(
    //                 child: Text(home_have_no_device_alert_text.tr),
    //               ),
    //               SizedBox(height: 30.w,),
    //               Container(
    //                 child: Row(
    //                   mainAxisAlignment: MainAxisAlignment.spaceAround,
    //                   children: [
    //                     GestureDetector(
    //                       onTap: (){
    //                         SmartDialog.dismiss();
    //                       },
    //                       child: Container(
    //                         width: 200.w,
    //                         height: 90.w,
    //                         alignment: Alignment.center,
    //                         decoration: BoxDecoration(
    //                             color: Colors.grey,
    //                             borderRadius: BorderRadius.circular(20.w)
    //                         ),
    //                         child: Text(alert_waring_canclebtn_text.tr),
    //                       ),
    //                     ),
    //                     GestureDetector(
    //                       onTap: (){
    //                         SmartDialog.dismiss();
    //                         Navigator.of(context).pushNamed('AddDevicePage').then((val){
    //                           _getList();
    //                         });
    //                       },
    //                       child: Container(
    //                         width: 200.w,
    //                         height: 90.w,
    //                         alignment: Alignment.center,
    //                         decoration: BoxDecoration(
    //                             color: themeColor,
    //                             borderRadius: BorderRadius.circular(20.w)
    //                         ),
    //                         child: Text(alert_waring_surebtn_text.tr),
    //                       ),
    //                     )
    //                   ],
    //                 ),
    //               )
    //             ],
    //           ),
    //         ),
    //       );
    //     }
    // );
  }

  Widget _buildHomeNoData(int type){
    String imgurl = '';
    String title = '';
    String content = '';
    String btnTitle='';
    if(type == 1){
      imgurl = 'assets/home/home_no_device.png';
      title = 'No device added'.tr;
      content = 'Add your device to get more information.'.tr;
      btnTitle = 'Add Device'.tr;
    }else if(type == 2){
      imgurl = 'assets/home/home_no_network.png';
      title = 'Network not Connected'.tr;
      content = 'Since the network is not connected\n you won\'t be able to view the data.'.tr;
      btnTitle = 'Device Network Setting'.tr;
    }
    return Container(
      child: Column(
        children: [
          SizedBox(height: ScreenUtil().statusBarHeight+0.w,),
          _topWidget(),
          SizedBox(height: 240.h,),
          Image.asset(imgurl,width: 480.w,),
          SizedBox(height: 48.h,),
          Container(
            child: Text(title,style: TextStyle(
              color: Colors.white,
              fontSize: 32.sp,
            ),),
          ),
          SizedBox(height: 24.h,),
          Container(
          padding: EdgeInsets.symmetric(horizontal: 40.w),
            child: Text(content,style: TextStyle(
              color: Color.fromRGBO(255, 255, 255, 0.5),
              fontSize: 28.sp,
            ),textAlign: TextAlign.center,),
          ),
          SizedBox(height: 60.h,),
          GestureDetector(
            onTap: (){
              if(type == 1){
                _showNoDeviceAlert();
              }else if(type == 2){
                Navigator.of(context).pushNamed('DeviceNetPage');
              }
            },
            child: Container(
              width: 690.w,
              height: 90.w,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                  color: themeColor,
                  borderRadius: BorderRadius.circular(12.w)
              ),
              child: Text(btnTitle,style: TextStyle(
                  color: Colors.white,
                  fontSize: 32.sp
              ),),
            ),
          )
        ],
      ),
    );
  }

  Widget _topWidget(){
    return Container(
      color: Colors.transparent,
      padding: EdgeInsets.symmetric(horizontal: 30.w),
      height: 44,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          GestureDetector(
            onTap: (){
              _showDeviceChoose();
              // eventBus.fire(IndexSliderChange(true));
              // setState(() {
              //   isopen = true;
              // });
              // if(drawerKey.currentState != null && drawerKey.currentState!.isDrawerOpen){
              //   drawerKey.currentState?.closeSlider();
              //   eventBus.fire(IndexSliderChange(false));
              //   setState(() {
              //     isopen = false;
              //   });
              // }else{
              // eventBus.fire(IndexSliderChange(true));
              // drawerKey.currentState?.openSlider();
              // setState(() {
              //   isopen = true;
              // });
              // }
            },
            child: Row(
              children: [
                // Container(
                //   child: Image.asset('assets/home/home_person.png',width: 64.w,),
                // ),
                // SizedBox(width: 20.w,),
                Visibility(visible: true,child: Container(
                  constraints: BoxConstraints(
                      maxWidth: 260.w
                  ),
                  child: Text(baseUserInfo['firstName']!=null? baseUserInfo['firstName']:baseUserInfo['nickname']??'user',style: TextStyle(
                      color: whiteFontColor,
                      fontSize: 40.sp,
                      fontWeight: FontWeight.w600
                  ),maxLines: 1,overflow: TextOverflow.ellipsis,),
                ),),
                SizedBox(width: 6.w,),
                Image.asset('assets/common/control_down.png',width: 48.w,)
              ],
            ),
          ),
          Visibility(child: Container(
            child: Text(cndcValue.isNotEmpty && double.parse('${cndcValue ?? '0'}') <0?'Discharging'.tr: cndcValue.isNotEmpty && double.parse('${cndcValue ?? '0'}') >0?'Charging'.tr:'Ready'.tr,style: TextStyle(
                color:cndcValue.isNotEmpty && double.parse('${cndcValue ?? '0'}') <0? themeColor : Color(0xff06df85),
                fontSize: 28.sp,
                fontWeight: FontWeight.w600
            ),maxLines: 1,overflow: TextOverflow.ellipsis,),
          ),visible: baseDevice != null && baseDevice?['status'].toString() != '2',),
          // Container(
          //   child: Image.asset('assets/home/home_logo.png',height: 40.w,),
          // )
          // GestureDetector(
          //   onTap: (){
          //     JhPickerTool.showStringPicker(context,
          //         data: _list,
          //         clickCallBack: _selectType,
          //         normalIndex: 0);
          //   },
          //   child: Row(
          //     children: [
          //       SizedBox(width: 20.w,),
          //       Text(home_page_change_device_text.tr,style: TextStyle(
          //           color: fontColor
          //       ),)
          //     ],
          //   ),
          // ),
        ],
      ),
    );
  }

  _showDeviceChoose(){
    return SmartDialog.show(builder: (ctx){
      return TopDeviceSelect(
        callBack: (type){
          _getDatas(type: 1);
          if(type == 1){
            _showAddDeviceAlert();
          }
        },
      );
    },alignment: Alignment.topCenter,animationTime: Duration(milliseconds: 200));
  }

  _showAddDeviceAlert(){
    SmartDialog.show(builder: (ctx){
      return Container(
        height: 530.w,
        padding: EdgeInsets.only(left: 48.w,right: 48.w,top: 32.w,bottom: 48.w),
        decoration: BoxDecoration(
            color: Color(0xff1E1E1E),
            borderRadius: BorderRadius.only(topLeft: Radius.circular(32.w),topRight: Radius.circular(32.w))
        ),
        child: Column(
          children: [
            Container(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text('Add new device',style: TextStyle(
                      color: Colors.white,
                      fontSize: 28.sp,
                      fontWeight: FontWeight.w600
                  ),),
                  GestureDetector(
                    onTap: (){
                      SmartDialog.dismiss();
                    },
                    child: Icon(Icons.close,size: 30.sp,color: Color(0xff999999),),
                  )
                ],
              ),
            ),
            SizedBox(height: 100.w,),
            GestureDetector(
              onTap: (){
                SmartDialog.dismiss();
                getCameraPermission(context, (){
                  Navigator.of(context).pushNamed('ScanPage').then((val){
                    if(mounted){setState(() {});}
                  });
                });
              },
              child: Container(
                height: 108.w,
                width: 654.w,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                    color: themeColor,
                    borderRadius: BorderRadius.circular(8.w)
                ),
                child:Text('Scan Your Device',style: TextStyle(
                    color: Colors.white,
                    fontSize: 28.sp,
                    fontWeight: FontWeight.w600
                ),),
              ),
            ),
            SizedBox(height: 32.w,),
            GestureDetector(
              onTap: (){
                SmartDialog.dismiss();
                Navigator.of(context).pushNamed('MinAddDeviceInput').then((val){
                  print('base===' + baseDevice.toString());
                  setState(() {});
                });
              },
              child: Container(
                height: 108.w,
                width: 654.w,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                    color: Color(0xff2A2A2A),
                    borderRadius: BorderRadius.circular(8.w)
                ),
                child:Text('Manual Entry'.tr,style: TextStyle(
                    color: Colors.white,
                    fontSize: 28.sp,
                    fontWeight: FontWeight.w600
                ),),
              ),
            ),
          ],
        ),
      );
    },alignment: Alignment.bottomCenter);
  }

  List<Widget> _charts(){
    return [
      Column(
      children: [
        Visibility(visible: selType == 0,child: Container(
          child: Column(
            children: [
              Container(
                height: 600.h,
                width: 1.sw,
                color: Colors.transparent,
                child:
                selIndex != 0?
                    selIndex == 4 && isShowBar != '1'?
                    LineChartSample4(datas: socdatas??[],values: socvalues??[],selType: 1,selIndex: selIndex,unit: socunit,):
                BarChartSample5(datas: socdatas??[],values: socvalues??[],selType: 1,selIndex: selIndex,unit: socunit,isRef:isRef)
                    : LineChartSample4(datas: socdatas??[],values: socvalues??[],selType: 1,selIndex: selIndex,unit: socunit,),
              ),
              Container(
                padding: EdgeInsets.symmetric(horizontal: 40.w,),
                margin: EdgeInsets.only(top: 26.h),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    GestureDetector(
                      onTap: (){
                        setState(() {
                          isShowBattery = !isShowBattery;
                        });
                      },
                      child: Container(
                        color: Colors.transparent,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text('Battery'.tr,style: TextStyle(
                                color: Colors.white,
                                fontSize: 32.sp,
                                height: 1.6,
                                fontWeight: FontWeight.w600
                            ),maxLines: 1,overflow: TextOverflow.ellipsis,),
                            Image.asset(isShowBattery?'assets/common/control_up.png':'assets/common/control_down.png',width: 40.w,)
                          ],
                        ),
                      ),
                    ),
                    SizedBox(height: 12.w,),
                    Visibility(visible: isShowBattery,child: Column(
                      children: [
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Container(
                              width: 12.w,
                              height: 12.w,
                              decoration: BoxDecoration(
                                  border: Border.all(color: themeColor,width: 1.w),
                                  borderRadius: BorderRadius.circular(12.w),
                                  gradient: LinearGradient(
                                      colors: [
                                        Color(0x5f233292),
                                        Color(0x0f3c55f8),
                                      ],
                                      begin: Alignment.topCenter,
                                      end: Alignment.bottomCenter
                                  )
                              ),
                            ),
                            SizedBox(width: 12.w,),
                            Text('Discharged'.tr,style: TextStyle(
                                color: Color.fromRGBO(255, 255, 255, 0.5),
                                fontWeight: FontWeight.w400,
                                fontSize: 28.sp,
                                height: 1
                            ),)
                          ],
                        ),
                        SizedBox(height: 16.w,),
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Container(
                              width: 12.w,
                              height: 12.w,
                              decoration: BoxDecoration(
                                  border: Border.all(color: Color(0xffCD9604),width: 1.w),
                                  borderRadius: BorderRadius.circular(12.w),
                                  gradient: LinearGradient(
                                      colors: [
                                        Color(0x0fcd9607),
                                        Color(0x5f674b04),
                                      ],
                                      begin: Alignment.topCenter,
                                      end: Alignment.bottomCenter
                                  )
                              ),
                            ),
                            SizedBox(width: 12.w,),
                            Text('Charged'.tr,style: TextStyle(
                                color: Color.fromRGBO(255, 255, 255, 0.5),
                                fontWeight: FontWeight.w400,
                                fontSize: 28.sp,
                                height: 1
                            ),)
                          ],
                        ),
                        SizedBox(height: 24.w,)
                      ],
                    ),),
                  ],
                ),
              ),
            ],
          ),
        ),),
        Visibility(visible: selType != 0 || selType == 0 && isShowBattery,child: Container(
          height: selType ==0? 600.h:900.h,
          width: 1.sw,
          child: Column(
            children: [
              Expanded(child: Container(
                color: Colors.transparent,
                width: 1.sw,
                child:
                selIndex != 0?
                selIndex == 4 && isShowBar != '1'?
                LineChartSample4(datas: datas??[],values: values??[],selType: selType,selIndex: selIndex,unit: unit,):
                BarChartSample5(datas: datas??[],values: values??[],selType: selType,selIndex: selIndex,unit: unit,bottomValues: bottomValues,isRef:isRef)
                    : LineChartSample4(datas: datas??[],values: values??[],selType: selType,selIndex: selIndex,unit: unit,),
              )),
            ],
          ),
        ),),
      ],
    )
    ];
  }

  void _showSelectDialog(){
    SmartDialog.show(builder: (ctx){
      return MonitorStaticChooseDateDialog(selIndex: selIndex,selType: selType,onDateChange: (index,type,times){
        setState(() {
          selIndex = index;
          selType = type;
          dateTimes = times;
          _getYMRStr();
        });
        _getDatas();
      },times: dateTimes,);
    },alignment: Alignment.bottomCenter);
  }



  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
